package org.apache.ibatis.type;

import com.alibaba.fastjson.JSON;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(JSON.class)
public class JsonTypeHandler extends BaseTypeHandler<JSON> {

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSON json, JdbcType jdbcType) throws SQLException {
      if(json == null){
          preparedStatement.setString(i, null);
      }
      else{
          preparedStatement.setString(i, json.toJSONString());
      }
  }

  @Override
  public JSON getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
      String value = resultSet.getString(columnName);
      if(value == null){
          return null;
      }
      if(value.startsWith("[") || value.endsWith("]")){
          return JSON.parseArray(value);
      }
      else if(value.startsWith("{") || value.endsWith("}")){
          return JSON.parseObject(value);
      }
      return null;
  }

  @Override
  public JSON getNullableResult(ResultSet resultSet, int i) throws SQLException {
    return null;
  }

  @Override
  public JSON getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
    return null;
  }
}